//
//  WQCLoginViewController.swift
//  3-微博
//
//  Created by DDDD on 16/2/27.
//  Copyright © 2016年 gongsimingzi. All rights reserved.
//

import UIKit
import AFNetworking

class WQCLoginViewController: UIViewController,UIWebViewDelegate {

    var webView :UIWebView?
    
    override func loadView() {
        webView = UIWebView()
        
        webView?.delegate = self
        
        view = webView
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNav()
        
        view.backgroundColor = UIColor.whiteColor()
        
        
//        第一步: App提供一个网页(网页内容是由服务器提供的)
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(app_KEY)&redirect_uri=\(app_URL)&response_type=code")!
        
//        print(url)
        
        let request = NSURLRequest(URL: url)
        
        webView?.loadRequest(request)
        
//        第二步: 我们可以在网页里输入用户名和密码  auto方法中自动填写
        
//        第三步: 服务器会验证用户名和密码,然后返回网页一个 Code
        //webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool 
        
//        第四步: App通过一定的方式来获取Code
//        第五步: App通过这个Code来向服务器请求换取Token
        // 第六步: 服务器验证一下Code,然后返回给App,Token
        ////loadToken()
//        第七步: App可以通过Token来获取授权用户的数据
        
        
        // Do any additional setup after loading the view.
    }

    func setupNav(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "auto")
//        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
//        
//        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "auto")
    }
    
    func dismiss(){
//        print("dismiss")
        
        dismissViewControllerAnimated(true) { () -> Void in
            
        }

    }
    func auto(){
//    print("auto")
        //document.getElementById("userId").value = "wangqingchao@vip.qq.com"
        //document.getElementById("passwd").value="itcast123456"
        let js = "document.getElementById(\"userId\").value = \"wangqingchao@vip.qq.com\";document.getElementById(\"passwd\").value=\"Wang19891012\""
        webView?.stringByEvaluatingJavaScriptFromString(js)
    }
}



extension WQCLoginViewController {

    func webViewDidStartLoad(webView: UIWebView) {
        
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //absolute  绝对的
        //url的绝对路径,可以将url转换成string
//        print(request.URL?.absoluteString)
              if let urlstring = request.URL?.absoluteString{
        
                // 前缀 -- url.hasPrefix(<#T##prefix: String##String#>)
                // 后缀 -- url.hasSuffix(<#T##suffix: String##String#>)
            if urlstring.hasPrefix(app_URL){
                //query :可分离 url中 ?后的 key = value
                if let code = request.URL?.query{
                    
                    let subcode = code.substringFromIndex("code=".endIndex)
//                    print(subcode)
                  WQCUserViewModel().loadToken(subcode,success:{()->() in
//                        print("成功")
//                       self.dismiss()
                    NSNotificationCenter.defaultCenter().postNotificationName(kNotificaionChangeRootVC, object: nil)
                    self.dismissViewControllerAnimated( true, completion: { () -> Void in
                        
                    })
                        },failed:{() ->() in
//                            print("失败")
                            self.dismiss()
                    })
                }
            }
        }
        return true
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
    }

}

